#!/usr/bin/env python
#encoding:utf-8
from Tkinter import *
import tkFileDialog
import tkMessageBox
#import multiprocessing
import time
import threading
import os

from thread2 import Thread
from AutoPurchase import read_csvfile, open_browser,  autoInputCount, close_browser
from AutoPurchase import Login_1688,getInfo
from writeLog import logInfo


#Tkinter创建个小型的界面，方便于人的操作

addrstr = """

#收货地址
[receiveInfo]                          

#收货人姓名
inputUser     =  收货人姓名

#省市
province      =  广东

#城市
city          =  深圳市

#城市区域
area          =  龙岗

#街道地址
inputAddr     = 坂田5和大道

#邮编
inputPost     = 000000

#手机
inputMobile   = 17072088608

#区号,如 0777
phoneCode     = ""

#号码，如:87582688
phoneNum       = ""

#分机号,如12
phoneSub       = ""



[userPass]
#1688登录用户与密码

username = admin
password = admin




[url]                                        
url1688 = https://login.1688.com/member/signin.htm
"""

if not os.path.exists("config"):
	os.mkdir("config")
global infoFilename

infoFilename = "config/info.ini"

if os.path.exists(infoFilename):
	infoFile = open(infoFilename,"r")
	addrstr = infoFile.read()
	infoFile.close()


#创建横条型框架
def frame(root,side):
	w = Frame(root)
	w.pack(side = side, expand = YES, fill = BOTH)
	
#创建按钮	
def button(root, side, text, command = None):
	w = Button(root, text = text,width="10",height="2" ,command = command)
	w.pack(side = side, expand = YES, fill = BOTH, padx="20",pady="10")
	return w	

	
class MainFrame(Frame):
	def __init__(self):
		Frame.__init__(self)
		self.pack(expand = YES, fill = BOTH)
		self.master.title(u"1688下单")
		self.display = StringVar()
		self.cookie = {}
		self.driver = ""
		self.T_Mid_addr = ""
		#self.jobs = []
		self.isT = False
		self.t = None
		
		display = self.display
		root = frame(self,TOP)
		frm = Frame(root)
		
		frm_T = Frame(frm)
		Label(frm_T, text=u"文件名:").pack(side=LEFT)
		Entry(frm_T, textvariable = display ).pack(side=LEFT,expand=YES, fill = BOTH, padx = "1")
		bf = Button(frm_T,text=u"查找文件" , width="10",height="2" ,command = self.dialog)
		bf.pack(side = RIGHT, expand = YES, pady="1")
		frm_T.pack(side=TOP,fill=BOTH)

		frm_Mid = Frame(frm)
		#T_Mid = Text(frm_Mid, height='10').pack(fill=BOTH,expand = YES)
		T_Mid = Text(frm_Mid,width='90', height='5')
		T_Mid.pack(fill=BOTH,expand = YES)
		
		self.T_Mid_addr = Text(frm_Mid,width='90',height='15')
		self.T_Mid_addr.pack(fill=BOTH,expand = YES)
		self.T_Mid_addr.insert(INSERT,addrstr)
		frm_Mid.pack(side=TOP)
		self.T_Mid = T_Mid

		frm_footer = Frame(frm)
		button(frm_footer, LEFT, u"开始", command=self.mainStart)
		button(frm_footer, RIGHT,u"退出", command = self.myquit)

		frm_footer.pack(side=TOP)
		frm.pack(side=TOP)

	
	def dialog(self):
		filename = tkFileDialog.askopenfilename()
		print filename
		self.display.set(filename)
		filename =  self.display.get()
		self.T_Mid.insert(INSERT, filename+"\n")

	def mainStart(self):
		self.writeInfoFile()
		getInfo()
		filelines = ""
		filename =  self.display.get()
		#self.T_Mid.insert(INSERT, filename+"\n")
		#print filename
		#tkMessageBox.showinfo("filename",filename)
		if filename:
			filelines = read_csvfile(filename)
		else:
			tkMessageBox.showinfo("Error","请查找文件再继续!")
		if filelines:
			if self.t and self.t.is_alive(): pass
			else: self.isT = False
			if self.isT:
				tkMessageBox.showinfo("Running","Firexfox正在运行...")
				return
			self.t = Thread(target=self.procMain,args=(filelines,))
			#self.t = threading.Thread(target=self.procMain,args=(filename,))			
			self.isT = True
			self.t.start()
			pass
	def procMain(self,filelines):
		driver = open_browser()
		self.driver = driver
		if not self.driver:
			tkMessageBox.showinfo("Error","请安装 Firefox浏览器!")
			return 
		if not self.cookie:
			#pass
			Login_1688(driver)
			self.cookie = driver.get_cookies()
		else:
			Login_1688(driver)
			#driver.add_cookie(self.cookie)
		autoInputCount(filelines,driver).loopInput()
		self.isT = False
		#tkMessageBox.showinfo("down","已完成所有可以自动完成的!")
		close_browser(driver)

	def writeInfoFile(self):
		global infoFilename
		try:
			infoFile = open(infoFilename,"w")
			infoAddrStr = self.T_Mid_addr.get(1.0,END)
			infoFile.write(infoAddrStr)
			infoFile.close()
		except Exception,e:
			logInfo("Write info.ini Error,%s"%e)
	def myquit(self):
		if self.driver: close_browser(self.driver)
		if self.t and self.t.isAlive(): self.t.terminate()
		self.master.destroy()

			
if __name__ == "__main__":
	MainFrame().mainloop()
